﻿using FarPoint.Web.Spread;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace ControlExplorer
{
  public class SpreadDemoPage : Page
  {
    public const string IMAGE_FOLDER = "~/samples/images";

    private static string skin = null;

    protected virtual bool ApplyGlobalSkin
    {
      get { return false; }
    }

    protected virtual bool UnchangeSkin(FpSpread spread)
    {
      return false;
    }

    protected override void OnLoad(EventArgs e)
    {
      if (ApplyGlobalSkin)
      {
        if (!this.IsPostBack || Request.Form["__EVENTTARGET"] == "theme_switcher")
        {
          SheetSkin selectedSkin = null;
          if (IsPostBack)
          {
            if (Request.Form["__EVENTTARGET"] == "theme_switcher")
            {
              skin = Request.Form["__EVENTARGUMENT"];
              selectedSkin = DefaultSkins.Find(skin);
            }
          }
          if (!string.IsNullOrEmpty(skin))
          {
            selectedSkin = DefaultSkins.Find(skin);
            HtmlSelect themSwitcher = FindThemeSwitcher();
            if (themSwitcher != null)
            {
              for (int i = 0; i < themSwitcher.Items.Count; i++)
              {
                System.Web.UI.WebControls.ListItem item = themSwitcher.Items[i];
                if (item.Value.Equals(skin, StringComparison.OrdinalIgnoreCase))
                {
                  item.Selected = true;
                  break;
                }
              }
            }
          }

          List<FpSpread> ss = new List<FpSpread>();
          GetSpreads(null, ss);
          if (ss.Count > 0)
          {
            foreach (FpSpread s in ss)
            {
              if (UnchangeSkin(s)) continue;

              if (s.ActiveSheetView != null)
              {
                ContextMenuStyle bk = s.ActiveSheetView.ContextMenuStyle;
                s.ActiveSheetView.ActiveSkin = selectedSkin;
                s.ActiveSheetView.ContextMenuStyle = bk;
              }
            }
          }
        }
      }
      else
      {
        HtmlSelect themSwitcher = FindThemeSwitcher();
        themSwitcher.Visible = false;
      }

      base.OnLoad(e);
    }

    private HtmlSelect FindThemeSwitcher()
    {
      ContentPlaceHolder headerHolder = Master != null && Master.Master != null ? (ContentPlaceHolder)Master.Master.FindControl("HeaderButtons") : null;
      if (headerHolder != null)
      {
        return (HtmlSelect)headerHolder.FindControl("themeswitcher");
      }
      return null;
    }

    private void GetSpreads(Control root, List<FpSpread> result)
    {
      if (root == null) root = this;
      foreach (Control c in root.Controls)
      {
        if (c is FpSpread)
          result.Add(c as FpSpread);
        else
          GetSpreads(c, result);
      }
    }
  }
}